// 禁用Visual Studio的安全函数警告
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

// 函数声明
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
void showMenu();

int main() {
    double num1, num2, result;
    char operator;
    int continueCalculation = 1;
    
    printf("===== 简易计算器 =====\n");
    
    while (continueCalculation) {
        showMenu();
        
        // 获取用户输入
        printf("\n请输入第一个操作数: ");
        if (scanf("%lf", &num1) != 1) {
            printf("输入错误，请输入有效的数字！\n");
            // 清除错误输入
            while (getchar() != '\n');
            continue;
        }
        
        printf("请输入运算符 (+, -, *, /): ");
        // 清除缓冲区，防止之前的换行符被读取
        while (getchar() != '\n');
        if (scanf("%c", &operator) != 1) {
            printf("输入错误，请输入有效的运算符！\n");
            while (getchar() != '\n');
            continue;
        }
        
        printf("请输入第二个操作数: ");
        if (scanf("%lf", &num2) != 1) {
            printf("输入错误，请输入有效的数字！\n");
            // 清除错误输入
            while (getchar() != '\n');
            continue;
        }
        
        // 根据运算符执行相应的操作
        switch (operator) {
            case '+':
                result = add(num1, num2);
                printf("\n%.2lf + %.2lf = %.2lf\n", num1, num2, result);
                break;
            case '-':
                result = subtract(num1, num2);
                printf("\n%.2lf - %.2lf = %.2lf\n", num1, num2, result);
                break;
            case '*':
                result = multiply(num1, num2);
                printf("\n%.2lf * %.2lf = %.2lf\n", num1, num2, result);
                break;
            case '/':
                if (num2 == 0) {
                    printf("\n错误: 除数不能为零!\n");
                } else {
                    result = divide(num1, num2);
                    printf("\n%.2lf / %.2lf = %.2lf\n", num1, num2, result);
                }
                break;
            default:
                printf("\n错误: 无效的运算符!\n");
        }
        
        // 询问用户是否继续计算
        char choice;
        printf("\n是否继续计算? (y/n): ");
        while (getchar() != '\n');  // 清除缓冲区
        if (scanf("%c", &choice) != 1) {
            choice = 'n';  // 默认不继续
        }
        
        if (choice != 'y' && choice != 'Y') {
            continueCalculation = 0;
        }
        
        printf("\n----------------------------------------\n");
    }
    
    printf("\n感谢使用计算器，再见!\n");
    return 0;
}

// 函数定义
double add(double a, double b) {
    return a + b;
}

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    return a / b;
}

void showMenu() {
    printf("\n支持的运算:\n");
    printf("1. 加法 (+)\n");
    printf("2. 减法 (-)\n");
    printf("3. 乘法 (*)\n");
    printf("4. 除法 (/)\n");
}